#!/bin/bash -ex
# Copyright (c) Contributors to the Apptainer project, established as
#   Apptainer a Series of LF Projects LLC.
#   For website terms of use, trademark policy, privacy policy and other
#   project policies see https://lfprojects.org/policies

# this script runs as root under docker --privileged

# install dependencies
yum install -y rpm-build make yum-utils gcc binutils util-linux-ng which git
yum install -y libseccomp-devel cryptsetup
if [ $OS_TYPE != fedora ]; then
  yum install -y epel-release
fi
yum install -y golang fakeroot
yum install -y autoconf automake libtool pkgconfig fuse3-devel zlib-devel

# switch to an unprivileged user with sudo privileges
yum install -y sudo
useradd -u 1000 --create-home -s /bin/bash testuser
echo "Defaults:testuser env_keep=DOCKER_HOST" >>/etc/sudoers
echo "testuser ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
mkdir -p /local
chown -R testuser . /local

# Be careful not to use unescaped single quotes in these commands
su testuser -c '
  set -x
  set -e
  ./mconfig --only-rpm
  GOURL="$(sed -n "s/^Source1: //p" apptainer.spec)"
  if [ -n "$GOURL" ]; then
    GOSRC="$(basename $GOURL)"
    curl -f -L -sS -o $GOSRC $GOURL
    if [ -n "'$GO_ARCH'" ]; then
      # Download and install binary too to avoid rpm having to compile the
      #  go toolchain from source
      GOBIN="$(echo "$GOSRC"|sed "s/\.src./.'$GO_ARCH'./")"
      curl -f -L -sS https://golang.org/dl/$GOBIN | tar -xzf - -C /local
      PATH=/local/go/bin:$PATH
    fi
  fi
  go version
  ./scripts/download-dependencies
  if [ "$HIDE_DIST" = true ]; then
    # eliminate the "dist" part in the rpm name, for the release_assets
    echo "%dist %{nil}" >$HOME/.rpmmacros
  fi
  make -C builddir rpm
  sudo yum install -y $HOME/rpmbuild/RPMS/*/*.rpm
  BLD="$(echo $HOME/rpmbuild/BUILD/apptainer-*)"
  export GOPATH=$BLD/gopath
  PATH=$GOPATH/bin:$PATH

  apptainer exec oras://ghcr.io/apptainer/alpine:3.15.0 /bin/true

  # copy the rpms into the current directory for later use
  cp $HOME/rpmbuild/SRPMS/*.rpm $HOME/rpmbuild/RPMS/*/*.rpm .

  # remove any downloaded files so tar files do not get into release assets
  rm -f $DOWNLOADEDFILES
'
